package com.sddongyun.proxy;

import com.sddongyun.common.RequestWrapper;
import com.sddongyun.common.ResponseWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.message.BasicHttpRequest;
import org.apache.http.util.EntityUtils;
import org.mitre.dsmiley.httpproxy.ProxyServlet;

import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Enumeration;
import java.util.Map;
import java.util.Set;

/**
 * 重写 医保 代理
 * @author Lenovo
 * @date 2021-04-1815:20
 */
@Slf4j
public class YbProxyServlet extends ProxyServlet {

    @Override
    protected void service(HttpServletRequest servletRequest, HttpServletResponse servletResponse) throws ServletException, IOException {
        service((RequestWrapper)servletRequest, (ResponseWrapper)servletResponse);
    }

    protected void service(RequestWrapper servletRequest, ResponseWrapper servletResponse) throws ServletException, IOException {

        if (servletRequest.getAttribute(ATTR_TARGET_URI) == null) {
            servletRequest.setAttribute(ATTR_TARGET_URI, this.targetUri);
        }

        if (servletRequest.getAttribute(ATTR_TARGET_HOST) == null) {
            servletRequest.setAttribute(ATTR_TARGET_HOST, this.targetHost);
        }

        String method = servletRequest.getMethod();
        String proxyRequestUri = this.rewriteUrlFromRequest(servletRequest);
        System.out.println("proxyRequestUri: "+proxyRequestUri+
                "-getContentLength："+ servletRequest.getHeader("Content-Length"));
        Object proxyRequest;
        if (servletRequest.getHeader("Content-Length") == null && servletRequest.getHeader("Transfer-Encoding") == null) {
            proxyRequest = new BasicHttpRequest(method, proxyRequestUri);
        } else {
            proxyRequest = this.newProxyRequestWithEntity(method, proxyRequestUri, servletRequest);
        }
        this.copyRequestHeaders(servletRequest, (HttpRequest)proxyRequest);
        this.setXForwardedForHeader(servletRequest, (HttpRequest)proxyRequest);

        //因请求 axis2 定义的webservice服务，添加后才能访问到
        ((HttpRequest) proxyRequest).setHeader("content-type","text/html;charset=utf-8");

        //处理请求 入参
//        this.handleReqeust(servletRequest);

        HttpResponse proxyResponse = null;
        try {
            proxyResponse = this.doExecute(servletRequest, servletResponse, (HttpRequest)proxyRequest);

            int statusCode = proxyResponse.getStatusLine().getStatusCode();
            servletResponse.setStatus(statusCode, proxyResponse.getStatusLine().getReasonPhrase());
            this.copyResponseHeaders(proxyResponse, servletRequest, servletResponse);
            if (statusCode == 304) {
                servletResponse.setIntHeader("Content-Length", 0);
            } else {
                this.copyResponseEntity(proxyResponse, servletResponse, (HttpRequest)proxyRequest, servletRequest);
            }
            //处理请求出参
//            this.handleResponse(servletResponse);
        } catch (Exception var11) {
            this.handleRequestException((HttpRequest)proxyRequest, var11);
        } finally {
            if (proxyResponse != null) {
                EntityUtils.consumeQuietly(proxyResponse.getEntity());
            }

        }

    }

    private void setXForwardedForHeader(HttpServletRequest servletRequest, HttpRequest proxyRequest) {
        if (this.doForwardIP) {
            String forHeaderName = "X-Forwarded-For";
            String forHeader = servletRequest.getRemoteAddr();
            String existingForHeader = servletRequest.getHeader(forHeaderName);
            if (existingForHeader != null) {
                forHeader = existingForHeader + ", " + forHeader;
            }

            proxyRequest.setHeader(forHeaderName, forHeader);
            String protoHeaderName = "X-Forwarded-Proto";
            String protoHeader = servletRequest.getScheme();
            proxyRequest.setHeader(protoHeaderName, protoHeader);
        }

    }

    /**
     * 处理请求 入参
     * @param servletRequest
     * @throws IOException
     */
    public void handleReqeust(HttpServletRequest servletRequest) throws IOException {
        RequestWrapper requestWrapper = new RequestWrapper(servletRequest);
        // 获取字符串
        String jsonParam = requestWrapper.getBodyString();
//        String jsonParam = ((RequestWrapper)servletRequest).getBodyString();
        log.info("医保请求： ", jsonParam);

    }

    /**
     * 处理请求 出参
     * @param proxyResponse
     * @throws IOException
     */
    public void handleResponse(HttpServletResponse proxyResponse) throws IOException {
//        String ret = EntityUtils.toStg(proxyResponse.getEntity(), "UTF-8");
////        System.out.println(ret);
        ResponseWrapper responseWrapper = new ResponseWrapper(proxyResponse);
//        ResponseWrapper responseWrapper = (ResponseWrapper)proxyResponse;
        String realRes = new String(responseWrapper.getContent(),"UTF-8");
        log.info("医保返回： "+realRes);
    }
}
